package com.m.security.filter;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import com.alibaba.fastjson.JSON;
import com.client.job.utils.DataResult;
import com.m.security.exceptions.UserLoginParamException;
import com.m.utils.AjaxLoginParamDto;
import com.m.utils.DataZipUtil;
import com.m.utils.GlobleSysUser;
import com.m.utils.ResponseFormatter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * jwt用户登录处理
 * 
 * @author monxz
 *
 * @date 2019年10月25日
 */

public class JWTLoginFilter extends UsernamePasswordAuthenticationFilter {

	private AuthenticationManager authenticationManager;
	
	


	public JWTLoginFilter(AuthenticationManager authenticationManager) {
		super();
		this.authenticationManager = authenticationManager;
	}

	
	
	/**
	 * 请求登录
	 */
	@Override
	public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res)
			throws AuthenticationException {

		try {
			AjaxLoginParamDto dto = getParamByRequest(req);
  			return authenticationManager
					.authenticate(new UsernamePasswordAuthenticationToken(dto.getUserName(),dto.getPassword(), new ArrayList<>()));
		} catch (Exception e) {
			ResponseFormatter.initResponse(res, DataResult.buildFail(e.getMessage()));
		}
		return null;
	}

	/**
	 * 登录成功
	 */
	@Override
	protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain,
			Authentication auth) throws IOException, ServletException {
		GlobleSysUser user =  (GlobleSysUser) auth.getPrincipal();
		String tokenJSON = DataZipUtil.zipString(JSON.toJSONString(user));
		ResponseFormatter.initResponse(res,  DataResult.buildSuccess(tokenJSON));
	}
	
	
	

	/**
	 * 从request中获取到登录请求
	 * 
	 * @param req
	 * @return
	 * @throws UserLoginParamException
	 */
	private AjaxLoginParamDto getParamByRequest(HttpServletRequest req) throws UserLoginParamException {

		AjaxLoginParamDto dto = new AjaxLoginParamDto();
		dto.setUserName(req.getParameter("username"));
		dto.setPassword(req.getParameter("password"));
		
	  if(dto.getUserName() == null) {
		throw new UserLoginParamException("用户名不能为空");
	 }
	
	 if(dto.getPassword() == null) {
		throw new UserLoginParamException("密码不能为空");
	 }
		
		return dto;
	}

}
